﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Security.Server;
using System.Data.Objects.SqlClient;
using Microsoft.LightSwitch.Details;



namespace LightSwitchApplication
{
    public partial class ApplicationDataService
    {
        partial void SellOrders_Inserted(SellOrder entity)
        {
            entity.Drug.Stock -= entity.Quantity;
        }

        partial void DrugsInShortage_PreprocessQuery(ref IQueryable<Drug> query)
        {           
            query = query.Where(drugs => drugs.Stock < drugs.MinimumStock && drugs.IsDiscontinued == false && 
                        (!(drugs.Supplies.Where(supplies => supplies.IsDiscontinued == false && 
                            supplies.PurchaseOrders.Any(orders => orders.IsClosed == false)).Any())||
                        (drugs.Supplies.Where(supplies => supplies.IsDiscontinued == false).Sum(supplies => 
                            supplies.PurchaseOrders.Where(orders => orders.IsClosed == false).Sum(orders => orders.Quantity))                            
                                < drugs.MinimumStock - drugs.Stock)));
        }

        /*
        partial void DrugsWithoutAvailableSupplies_PreprocessQuery(ref IQueryable<Drug> query)
        {
            query = query.Where(drugs => drugs.IsDiscontinued == false && 
                !drugs.Supplies.Where(supplies => supplies.IsDiscontinued == false).Any()); 
        }*/

        partial void SellOrders_Deleting(SellOrder entity)
        {
            entity.Drug.Stock += entity.Quantity;
            if (entity.SellOrderHeader.SellOrders.FirstOrDefault() == null)
                entity.SellOrderHeader.Delete();
        }

        partial void PurchaseOrders_Deleting(PurchaseOrder entity)
        {
            if (entity.IsClosed == true)
                entity.Supply.Drug.Stock -= entity.Quantity;
        }

        partial void PrescriptionsExpired_PreprocessQuery(int? PatientId, ref IQueryable<Prescription> query)
        {
            query = query.Where(Prescriptions => Prescriptions.SellOrders.Count() >= Prescriptions.Refills + 1 || Prescriptions.ErrMsg != null);
        }

        partial void PrescriptionsInTaking_PreprocessQuery(int? PatientId, ref IQueryable<Prescription> query)
        {
            query = query.Where(Prescriptions => Prescriptions.SellOrders.Where(SellOrders =>
                SqlFunctions.DateDiff("d", SellOrders.SellOrderHeader.CreatedTime, DateTime.Now) <= Prescriptions.TakingWeeks * 7).Any());  
        }

        partial void PrescriptionsFillable_PreprocessQuery(int? PatientId, ref IQueryable<Prescription> query)
        {
            query = query.Where(Prescriptions =>
                Prescriptions.ErrMsg == null && 
                (Prescriptions.SellOrders.Count() == 0 ||
                (Prescriptions.SellOrders.Count() < Prescriptions.Refills + 1 &&
                Prescriptions.SellOrders.Where(SellOrders =>
                    SqlFunctions.DateDiff("d", SellOrders.SellOrderHeader.CreatedTime, DateTime.Now) > Prescriptions.TakingWeeks * 7).Any()
                )));
        }

        partial void DrugsForPrescription_PreprocessQuery(string MedicalName, decimal? Dosage, int? TakingPerDay, int? TakingDaysPerWeek, int? TakingWeeks, DateTime? PatientDOB, bool? IsPhysicianAssistant, string Unit, ref IQueryable<Drug> query)
        {
            int age = -1;
            if (PatientDOB.HasValue)
            {
                DateTime now = DateTime.Today;
                age = now.Year - PatientDOB.Value.Year;
                if (PatientDOB > now.AddYears(-age)) age--;
            }

            query = query.Where(Drugs => Drugs.MedicalName == MedicalName && Drugs.IsDiscontinued == false && 
                Dosage >= Drugs.Dose && Unit == Drugs.Unit && (int)(Dosage * 10) % (int)(Drugs.Dose * 10) == 0 && Drugs.Stock * Drugs.Dose >= Dosage * TakingPerDay * TakingDaysPerWeek * TakingWeeks &&
                ((age < 0) || (Drugs.LegalAge == null || Drugs.LegalAge <= age)));

            if (IsPhysicianAssistant.HasValue && IsPhysicianAssistant.Value == true)
                query = query.Where(Drugs => Drugs.Type != "R");
        }

        partial void SellOrderHeaders_Validate(SellOrderHeader entity, EntitySetValidationResultsBuilder results)
        {
            if(!entity.SellOrders.Any())
                results.AddEntityError("Empty sell order header");
        }

        partial void SellOrdersInPeriod_PreprocessQuery(DateTime? StartDate, DateTime? EndDate, ref IQueryable<SellOrder> query)
        {
            DateTime? nextDay = null;
            if(EndDate.HasValue)
                nextDay = EndDate.Value.AddDays(1);
            
            query = query.Where(so => so.SellOrderHeader.CreatedTime >= StartDate && so.SellOrderHeader.CreatedTime < nextDay);
        }

        partial void PurchaseOrdersInPeriod_PreprocessQuery(DateTime? StartDate, DateTime? EndDate, ref IQueryable<PurchaseOrder> query)
        {
            DateTime? nextDay = null;
            if (EndDate.HasValue)
                nextDay = EndDate.Value.AddDays(1);

            query = query.Where(po => po.CreatedTime >= StartDate && po.CreatedTime < nextDay);
        }
    }
}
